package com.yx.changdao.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yx.changdao.common.annotation.AutoLog;
import com.yx.changdao.common.annotation.ShiroDesc;
import com.yx.changdao.common.data.Pager;
import com.yx.changdao.common.data.Result;
import com.yx.changdao.common.entity.Problem;
import com.yx.changdao.common.entity.ProblemDeal;
import com.yx.changdao.common.enums.ScoreEnum;
import com.yx.changdao.common.exception.AlertException;
import com.yx.changdao.common.utils.*;
import com.yx.changdao.common.vo.ProblemVo;
import com.yx.changdao.service.ProblemDealService;
import com.yx.changdao.service.ProblemService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 问题结果评分模块
 *
 * @Auther: xiapeixin
 * @create 2020/04/03 16:51
 */
@RestController
@RequestMapping("/problem/score")
public class ProblemScoreController {

    /**
     * 问题服务
     */
    @Autowired
    private ProblemService problemService;

    /**
     * 处理结果
     */
    @Autowired
    private ProblemDealService problemDealService;

    /**
     * 总控 评价 未评价列表
     */
    @AutoLog
    @GetMapping("/no/list")
    @RequiresPermissions("problem:score:list")
    @ShiroDesc("问题评价:列表")
    public Result noList(@RequestParam(value = "page") Long page,
                         @RequestParam(value = "limit", required = false) Integer limit) {

        if (limit == null) {
            limit = SysConst.LIMIT_PAGE;
        }
        // 分页配置
        Page<Problem> pager = new Page<>(page, limit);
        // 根据请求解析条件。
        QueryWrapper<Problem> qw = SysUtils.autoCnd(Problem.class);
        qw.orderByDesc(Problem.CREATE_TIME); //时间倒序

        qw.eq(Problem.IF_DEAL, 1) //已处理的 ,未评价
                .eq(Problem.IF_ASSESS, 0);

        IPage<ProblemVo> voIPage = problemService.pageNex(pager, qw);
        voIPage.getRecords().forEach(p -> p.setResidentIdcard(DesensitizationUtils.idEncrypt(p.getResidentIdcard())));

        Map<String, Object> map = new HashMap<>();
        map.put("list", voIPage.getRecords());
        map.put("pager", new Pager(voIPage));

        return Result.ok().data(map);
    }

    /**
     * 总控 评价 已评价列表
     */
    @AutoLog
    @GetMapping("/already/list")
    @RequiresPermissions("problem:score:list")
    @ShiroDesc("问题评价:列表")
    public Result alreadyList(@RequestParam(value = "page") Long page,
                              @RequestParam(value = "limit", required = false) Integer limit) {

        if (limit == null) {
            limit = SysConst.LIMIT_PAGE;
        }
        // 分页配置
        Page<Problem> pager = new Page<>(page, limit);
        // 根据请求解析条件。
        QueryWrapper<Problem> qw = SysUtils.autoCnd(Problem.class);
        qw.orderByDesc(Problem.CREATE_TIME); //时间倒序

        qw.eq(Problem.IF_DEAL, 1) //已处理的 ,已评价
                .eq(Problem.IF_ASSESS, 1);

        IPage<ProblemVo> voIPage = problemService.pageNex(pager, qw);

        Map<String, Object> map = new HashMap<>();
        map.put("list", voIPage.getRecords());
        map.put("pager", new Pager(voIPage));

        return Result.ok().data(map);
    }

    /**
     * 总控 评价 打回列表
     */
    @AutoLog
    @GetMapping("/back/list")
    @RequiresPermissions("problem:score:list")
    @ShiroDesc("问题评价:列表")
    public Result backList(@RequestParam(value = "page") Long page,
                           @RequestParam(value = "limit", required = false) Integer limit) {
        if (limit == null) {
            limit = SysConst.LIMIT_PAGE;
        }
        // 分页配置
        Page<Problem> pager = new Page<>(page, limit);
        // 根据请求解析条件。
        QueryWrapper<Problem> qw = SysUtils.autoCnd(Problem.class);
        qw.orderByDesc(Problem.CREATE_TIME); //时间倒序

        qw.eq(Problem.IF_DEAL, 2); //打回处理的

        IPage<ProblemVo> voIPage = problemService.pageNex(pager, qw);

        Map<String, Object> map = new HashMap<>();
        map.put("list", voIPage.getRecords());
        map.put("pager", new Pager(voIPage));

        return Result.ok().data(map);
    }


    /**
     * 总控 评价 问题查看
     */
    @AutoLog
    @GetMapping("/{proId}")
    public Result lookList(@PathVariable("proId") Integer proId) {

        Problem problem = problemService.getById(proId);

        ProblemVo problemVo = new ProblemVo();

        BeanUtils.copyProperties(problem, problemVo);

        ProblemDeal one = problemDealService.getOne(new QueryWrapper<ProblemDeal>() //最新处理结果
                .select(ProblemDeal.DEAL_CONTENT)
                .eq(ProblemDeal.PROBLEM_ID, problemVo.getId())
                .orderByDesc(ProblemDeal.CREATE_TIME).last("limit 0,1"));

        if (Faster.isNotNull(one)) {
            problemVo.setDealContent(one.getDealContent());
        } else {
            problemVo.setDealContent("");
        }

        problemVo.setAssessResultCon(ScoreEnum.result(problemVo.getAssessResult()));

        return Result.ok().data(problemVo);
    }


    /**
     * 总控 评价 打回
     */
    @AutoLog
    @PutMapping("/back")
    /*@RequiresPermissions("problem:score:back")
    @ShiroDesc("问题评价:打回")*/
    public Result back(@RequestParam("id") Integer proId,
                       @RequestParam(value = "info", required = false) String info) throws AlertException {

        if (!problemService.returnBack(proId, info)) {
            throw new AlertException("操作失败");
        }
        return Result.ok("打回成功");
    }

    /**
     * 总控 评价 评价
     */
    @AutoLog
    @PutMapping("/assess")
    /*@RequiresPermissions("problem:score:assess")
    @ShiroDesc("问题评价:评分")*/
    public Result assess(@RequestParam("id") Integer proId,
                         @RequestParam("type") Integer type) throws AlertException {

        if (!problemService.assess(proId, type)) {
            throw new AlertException("评价失败");
        }
        return Result.ok("评价成功");
    }

    /**
     * 总控 重新打分
     */
    @AutoLog
    @PutMapping("/reassess")
    public Result reassess(@RequestParam("id") Integer proId,
                           @RequestParam("type") Integer type) throws AlertException {
        if (!problemService.reassess(proId, type)) {
            throw new AlertException("重新评分失败");
        }
        return Result.ok("重新评分成功");
    }


    /**
     * type = 0 未评价
     * type = 1 已评价
     * type = 2 打回处理
     */
    @AutoLog
    @GetMapping("/export")
    public void export(@RequestParam("type") @Range(min = 0, max = 2) Integer type,
                       @RequestParam("ids") String ids) throws Exception {

        QueryWrapper<Problem> qw = SysUtils.autoCnd(Problem.class);

        if (type < 2) {
            qw.eq(Problem.IF_DEAL, 1); //已处理的
            qw.eq(Problem.IF_ASSESS, type);
        } else if (type == 2) {
            qw.eq(Problem.IF_DEAL, 2); //打回处理的
        }

        List<Integer> idls = Faster.batch2(ids);

        if (!idls.isEmpty()) {
            qw.in(Problem.ID, idls);
        }

        List<Problem> list = problemService.list(qw);

        List<ProblemVo> collect = list.stream().map(t -> {
            ProblemVo problemVo = new ProblemVo();
            BeanUtils.copyProperties(t, problemVo);
            ProblemDeal one = problemDealService.getOne(new QueryWrapper<ProblemDeal>() //最新处理结果
                    .select(ProblemDeal.DEAL_CONTENT)
                    .eq(ProblemDeal.PROBLEM_ID, t.getId())
                    .orderByDesc(ProblemDeal.CREATE_TIME).last("limit 0,1"));

            if (Faster.isNotNull(one)) {
                problemVo.setDealContent(one.getDealContent());
            } else {
                problemVo.setDealContent("");
            }
            problemVo.setAssessResultCon(ScoreEnum.result(problemVo.getAssessResult()));
            return problemVo;

        }).collect(Collectors.toList());


        List<String> cloudms = new ArrayList<>();
        cloudms.add("residentName:反馈居民姓名");
        cloudms.add("residentAddress:反馈居民地址");
        cloudms.add("residentIdcard:反馈居民身份证号");
        cloudms.add("residentPhone:反馈居民手机号");
        cloudms.add("category:意见建议类别");
        cloudms.add("industryCategory:意见建议行业类别");

        cloudms.add("contact1Name:联户人1姓名");
        cloudms.add("contact1Phone:联户人1手机号");
        cloudms.add("contact2Name:联户人2姓名");
        cloudms.add("contact2Phone: 联户人2手机号");

        cloudms.add("content:意见建议内容");
        cloudms.add("depName:承办部门");
        cloudms.add("difficultLevel:办理难度");
        cloudms.add("dealContent:最新处理结果");

        if(type==1){
            cloudms.add("assessResultCon:评价结果");
        }else if(type==0){
            cloudms.add("满意");
            cloudms.add("基本满意");
            cloudms.add("不满意");
        }


        ExcelImportExportUtils.writeExcelByCloum(collect, SysUtils.getResponse(), "导出", cloudms);
    }
}
